<?php

namespace app\bsadmin\controller;

use app\common\model\InviteAninterview;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Border;

use think\facade\Cache;
use think\facade\Session;
use think\facade\View;
use think\facade\Db;
use think\facade\Validate;
use app\common\controller\JobFair as JobFairController;
use app\common\model\JobFair as JobFairModel;
use app\common\model\JobFairBoothCate as JobFairBoothCateModel;
use app\common\model\JobFairBooth as JobFairBoothModel;
use app\common\model\JobFairCompany as JobFairCompanyModel;
use app\common\model\JobFairContacts as JobFairContactsModel;
use app\common\model\JobFairContent as JobFairContentModel;
use app\common\model\JobFairResume as JobFairResumeModel;
use app\common\model\JobFairVip as JobFairVipModel;
use app\common\controller\Vip as VipController;
use app\bsadmin\model\JobFairBoothStatus as JobFairBoothStatusModel;
use helper\Baidu;
use think\helper\Str;

class JobFair extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['title']) {
                $where[] = ['job.title', 'like', '%' . $G['title'] . '%'];
            }
            if ($G['status'] != 'all') {
                $where[] = ['job.status', '=', $G['status']];
            }
            $Data = JobFairModel::alias('job')->where($where)
                ->field('job.*')
                ->order('job.id desc')->paginate($G['pageSize'])
                ->each(function ($v) {
                    if ($v->sign_up_start_time && $v->sign_up_end_time) {
                        if ($v->sign_up_start_time <= time() && $v->sign_up_end_time >= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    } elseif ($v->sign_up_start_time) {
                        if ($v->sign_up_start_time <= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    } elseif ($v->sign_up_end_time) {
                        if ($v->sign_up_end_time >= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    }
                    if ($v->start_time && $v->end_time && !in_array($v->status, [1,])) {
                        if ($v->start_time <= time() && $v->end_time >= time()) {
                            $v->status = 2;
                        } else if ($v->end_time < time()) {
                            $v->status = 3;
                        } else {
                            $v->status = 0;
                        }
                    }
                    $v['sign_up_start_time'] = $v['sign_up_start_time'] ? date('Y-m-d H:m:s', $v['sign_up_start_time']) : '';
                    $v['sign_up_end_time'] = $v['sign_up_end_time'] ? date('Y-m-d H:m:s', $v['sign_up_end_time']) : '';
                    $v['start_time'] = $v['start_time'] ? date('Y-m-d H:m:s', $v['start_time']) : '';
                    $v['end_time'] = $v['end_time'] ? date('Y-m-d H:m:s', $v['end_time']) : '';
                    $v['thumb'] = $v['thumb'] ? config('web.imgurl') . $v['thumb'] : '';
                    $v['banner'] = $v['banner'] ? config('web.imgurl') . $v['banner'] : '';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }

    /**
     * @Notes:导出招聘会详情
     * @Author: hhm <huanghemao@xycms.com>
     * @DateTime: 2022/2/18 0018 下午 15:26
     */
    public function exportJobFair(){
        if (request()->post()){
            $D=request()->post();
            $jobFair=JobFairModel::find($D['ids']);
            $Field=[
                'jobFair.title,jobFair.jobs_sum,jobFair.view_sum,jobFair.view_people_sum,jobFair.resume_sum',
                'fairBooth.identifier,fairBooth.index,fairBooth.id as BoothId',
                'company.title as companyTitle,company.id as companyId'
            ];
            $Data=JobFairModel::alias('jobFair')
                ->where('jobFair.id',$jobFair->id)
                ->where('fairBooth.company_id is not null')
                ->join('job_fair_booth fairBooth','jobFair.id=fairBooth.jid')
                ->join('company company','fairBooth.company_id=company.id')
                ->field($Field)
                ->select()->each(function ($v){
                    //展位号
                    $v['identifierIndex']=$v['identifier'].$v['index'];
                    //职位数量
                    $v['jobNum']=JobsModel::where('company_id',$v['companyId'])->count();
                    //职位查看数量
                    $v['jobViews']=JobsModel::where('company_id',$v['companyId'])->sum("view");
                    //简历投递数量
                    $v['jobsResumeNum']=JobsDeliveryResume::where('company_id',$v['companyId'])->count();
                    //邀请面熟数量
                    $v['inviteViews']=InviteAninterview::where('company_id',$v['companyId'])->count();
                });
            if ($Data) {
                $title = [
                    ['title' => 'ID', 'key' => 'companyId'],
                    ['title' => '展位号', 'key' => 'identifierIndex'],
                    ['title' => '公司名称', 'key' => 'companyTitle'],
                    ['title' => '招聘职位数', 'key' => 'jobNum'],
                    ['title' => '投递简历数量', 'key' => 'jobsResumeNum'],
                    ['title' => '职位浏览数量', 'key' => 'jobViews'],
                    ['title' => '面试邀请数量', 'key' => 'inviteViews']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();
                $pDataType = DataType::TYPE_STRING;
                $sheet->setCellValueExplicit( "A1", $jobFair->title, $pDataType);
                $sheet->setMergeCells(["A1:G1"=>"A1:G1"]);
//                $sheet->setTitle($jobFair->title);
                $sheet->setTitle( mb_strimwidth($jobFair->title, 0, 28, "..."));
                //全局水平居中
                $spreadsheet->getDefaultStyle()->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
                $sheet->getDefaultColumnDimension()->setWidth(20); // 默认单元格宽度

                // 设置A2到K2的背景色，也可以单独指定单元格
                $sheet->getStyle('A1:G1')
                    ->getFill()
                    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) // 设置填充样式
                    ->getStartColor()
                    ->setARGB("FFCCCCCC"); // 可以忽略透明，直接使用RGB


                //表头
                //设置单元格内容
                $titCol = 'A';
                $titColA=$titCol;
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '2', $v['title']);
                    $titCol++;
                }
                $row = 3;
                $initial=$row;
                foreach ($Data as $item) {
                    $dataCol = 'A';
                    foreach ($title as $key => $v) {
                        $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
                        $dataCol++;
                    }
                    $row++;
                }
                $row+=3;
//                $sheet->setCellValue("{$titColA}{$row}","总计：");
                $formulaCol=['D','E','F','G'];
                foreach ($formulaCol as $v){
                    $sum=$row-1;
                    $sheet->setCellValue($v.$row, "=SUM({$v}{$initial}:{$v}{$sum})");
                }

                $colB="B";
                $countTitle=["总计：","参会企业总数：","求职者总数：","浏览人数：","浏览量："];
                $countValue=[$jobFair->company_sum,$jobFair->resume_sum,$jobFair->view_people_sum,$jobFair->view_sum];
                foreach ($countTitle as $k=>$v){
                    $sheet->setCellValue("{$titColA}{$row}",$v);
                    if ($k!=0){
                        $sheet->setCellValue("{$colB}{$row}", $countValue[$k-1]);
                    }
                    //行加粗
                    $sheet->getStyle($row)->getFont()->setBold(true);
                    $row++;
                }
                $row-=1;
                $sheet->getStyle("A1:G1")->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN);   // 上边框
                $sheet->getStyle("A{$row}:G{$row}")->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN);// 下边框
                $sheet->getStyle("A1:A{$row}")->getBorders()->getLeft()->setBorderStyle(Border::BORDER_THIN);  // 左边框
                $sheet->getStyle("G1:G{$row}")->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN); // 右边框

                $filename = 'output/company/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
            }
            return $this->ajaxReturn('暂无数据~', -100);
        }
    }

    public function recycleBin()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['title']) {
                $where[] = ['job.title', 'like', '%' . $G['title'] . '%'];
            }
            if ($G['status'] != 'all') {
                $where[] = ['job.status', '=', $G['status']];
            }
            $Data = JobFairModel::onlyTrashed()->alias('job')->where($where)
                ->field('job.*')
                ->order('job.delete_time desc')->paginate($G['pageSize'])
                ->each(function ($v) {
                    if ($v->sign_up_start_time && $v->sign_up_end_time) {
                        if ($v->sign_up_start_time <= time() && $v->sign_up_end_time >= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    } elseif ($v->sign_up_start_time) {
                        if ($v->sign_up_start_time <= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    } elseif ($v->sign_up_end_time) {
                        if ($v->sign_up_end_time >= time()) {
                            $v->status = 1;
                        } else {
                            $v->status = 0;
                        }
                    }
                    if ($v->start_time && $v->end_time) {
                        if ($v->start_time <= time() && $v->end_time >= time()) {
                            $v->status = 2;
                        } else {
                            $v->status = 3;
                        }
                    }
                    $v['sign_up_start_time'] = $v['sign_up_start_time'] ? date('Y-m-d H:m:s', $v['sign_up_start_time']) : '';
                    $v['sign_up_end_time'] = $v['sign_up_end_time'] ? date('Y-m-d H:m:s', $v['sign_up_end_time']) : '';
                    $v['start_time'] = $v['start_time'] ? date('Y-m-d H:m:s', $v['start_time']) : '';
                    $v['end_time'] = $v['end_time'] ? date('Y-m-d H:m:s', $v['end_time']) : '';
                    $v['thumb'] = $v['thumb'] ? config('web.imgurl') . $v['thumb'] : '';
                    $v['banner'] = $v['banner'] ? config('web.imgurl') . $v['banner'] : '';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }
    /**
     * 编辑文章
     */
    public function edit($id)
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'title'         => 'require',
                'content'       => 'require',
                'start_time'    => 'require',
                'end_time'      => 'require',
                'status'        => 'require',
                'thumb'         => 'require',
                'banner'        => 'require',
                'base_view'        => 'number|min:0',
                'base_company'        => 'number|min:0',
            ];
            $msg  =   [
                'title.require'         => '标题不能为空',
                'start_time.require'    => '请选择开始时间',
                'end_time.require'      => '请选择结束时间',
                'content.require'       => '详情不能为空',
                'status.require'        => '请选择状态',
                'thumb.require'         => '请上传封面',
                'banner.require'        => '请上传横幅',
                'base_view.number'      => '浏览数基准必须是数字',
                'base_view.min'         => '浏览数基准不能小于0',
                'base_company.number'   => '参会企业基准必须是数字',
                'base_company.min'      => '参会企业基准不能小于0'
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            if (!$D['online_registration'] && !$D['tel_registration'] && !$D['offline_registration'])
                return $this->ajaxReturn('请选择一种报名方式', -100);
            $JobFairModel = JobFairModel::where(['id' => $id])->find();
            $JobFairModel->title                = $D['title'];
            $JobFairModel->thumb                = $D['thumb'];
            $JobFairModel->banner               = $D['banner'];
            $JobFairModel->booth_img            = $D['booth_img'];
            $JobFairModel->status               = $D['status'];
            $JobFairModel->nature               = $D['nature'];
            $JobFairModel->online_registration  = $D['online_registration'];
            $JobFairModel->tel_registration     = $D['tel_registration'];
            $JobFairModel->offline_registration = $D['offline_registration'];
            $JobFairModel->sort                 = $D['sort'];
            $JobFairModel->is_all_sign_up       = $D['is_all_sign_up'];
            $JobFairModel->booth_sum            = $D['booth_sum'];
            $JobFairModel->base_view            = $D['base_view'] ?? 0;
            $JobFairModel->base_people_sum         = $D['base_people_sum'] ?? 0;
            if (strtotime($D['sign_up_start_time']))
                $JobFairModel->sign_up_start_time = strtotime($D['sign_up_start_time']);
            if (strtotime($D['sign_up_end_time']))
                $JobFairModel->sign_up_end_time = strtotime($D['sign_up_end_time']);
            if (strtotime($D['start_time']))
                $JobFairModel->start_time = strtotime($D['start_time']);
            if (strtotime($D['end_time']))
                $JobFairModel->end_time = strtotime($D['end_time']);

            if ($D['offline_registration'] && (empty($D['job_fair_area']) || empty($D['address'])))
                return $this->ajaxReturn('当使用线下报名时必须地区和详细地址', -100);
            $JobFairContentModel = JobFairContentModel::where(['jid' => $JobFairModel->id])->find();
            if (!empty($D['job_fair_area']) && count($D['job_fair_area']) >= 3) {
                $JobFairContentModel->job_fair_area1 = $D['job_fair_area'][0];
                $JobFairContentModel->job_fair_area2 = $D['job_fair_area'][1];
                $JobFairContentModel->job_fair_area3 = $D['job_fair_area'][2];
            }
            if (!empty($D['address']))
                $JobFairContentModel->address = $D['address'];
            $JobFairContentModel->lng = $D['lng'];
            $JobFairContentModel->lat = $D['lat'];
            $JobFairContentModel->transit = $D['transit'];
            $JobFairContentModel->content = $D['content'];
            $JobFairContentModel->about = $D['about'];
            $Contacts = [];
            if (!empty($D['contacts'])) {
                $JobFairContactsModel = new JobFairContactsModel;
                foreach ($D['contacts'] as $k => $v) {
                    $Contacts[$k] = [
                        'contacts'          =>  $v['contacts'],
                        'contacts_mobile'   =>  $v['contacts_mobile'],
                        'contacts_tel'      =>  $v['contacts_tel'],
                        'contacts_qq'       =>  $v['contacts_qq'],
                        'contacts_wechat'   =>  $v['contacts_wechat'],
                        'contacts_email'    =>  $v['contacts_email'],
                        'remarks'           =>  $v['remarks']
                    ];
                    if ($v['id'])
                        $Contacts[$k]['id'] = $v['id'];
                }
            }
            if ($D['tel_registration'] && empty($Contacts))
                return $this->ajaxReturn('当使用电话报名时必须设置联系人', -100);
            $BoothCate = [];
            $Booth = [];
            if (!empty($D['booth'])) {
                $booth_json = json_decode($D['booth'], true);
                if (!empty($booth_json)) {
                    $JobFairBoothModel = new JobFairBoothModel;
                    $JobFairBoothCateModel = new JobFairBoothCateModel;
                    foreach ($booth_json as $k => $v) {
                        $BoothCate[$k] = [
                            'name'              =>  empty($v['name']) ? $v['identifier'] . '区' : $v['name'],
                            'identifier'        =>  $v['identifier'],
                            'sum'               =>  $v['sum'],
                            'price'             =>  $v['price'],
                            'specifications'    =>  $v['specifications']
                        ];
                        if (!empty($v['id']))
                            $BoothCate[$k]['id'] = $v['id'];
                        $stock_sum = 0;
                        foreach ($v['boothCate'] as $key => $booth) {
                            if (!empty($booth['id'])) {
                                $Booth[] = [
                                    'id'                =>  $booth['id'],
                                    'identifier'        =>  $v['identifier'],
                                    'index'             =>  $booth['index'],
                                    'price'             =>  $booth['price'],
                                    'specifications'    =>  $booth['specifications'],
                                    'status'            =>  $booth['status'],
                                ];
                            } else {
                                $Booth[] = [
                                    'identifier'        =>  $v['identifier'],
                                    'index'             =>  $booth['index'],
                                    'price'             =>  $booth['price'],
                                    'specifications'    =>  $booth['specifications'],
                                    'status'            =>  $booth['status'],
                                ];
                            }
                            if ($booth['status'])
                                $stock_sum++;
                        }
                        $BoothCate[$k]['stock_sum'] = $v['sum'] - $stock_sum;
                    }
                }
            }
            if ($D['online_registration'] && (empty($BoothCate) || empty($Booth)))
                return $this->ajaxReturn('当使用线上报名时必须设置展位', -100);
            $Vip = [];
            $VipController = VipController::getCate();
            $JobFairVipModel = new JobFairVipModel;
            $VipControllerIndex = 0;
            foreach ($VipController as $v) {
                $Vip[$VipControllerIndex] = [
                    'vid'               =>  $v->id,
                    'level'             =>  $v->level,
                    'is_company'        =>  $v->is_company
                ];
                if ($D['is_all_sign_up']) {
                    $Vip[$VipControllerIndex]['status'] = 1;
                } else {
                    $Vip[$VipControllerIndex]['status'] = in_array($D['vip'], $v->id) ? 1 : 0;
                }
                $VipControllerIndex++;
            }
            unset($D);
            unset($rule);
            unset($msg);
            unset($Validate);
            unset($result);
            unset($booth_json);
            unset($VipController);
            unset($VipControllerIndex);
            // 启动事务
            Db::startTrans();
            try {
                $JobFairModel->save();
                $JobFairContentModel->jid = $JobFairModel->id;
                $JobFairContentModel->save();
                if (!empty($Contacts)) {
                    array_walk($Contacts, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairContactsModel->saveAll($Contacts);
                }
                if (!empty($BoothCate)) {
                    array_walk($BoothCate, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothCateModel->saveAll($BoothCate);
                }
                if (!empty($Booth)) {
                    array_walk($Booth, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothModel->saveAll($Booth);
                }
                if (!empty($Vip)) {
                    array_walk($Vip, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairVipModel->saveAll($Vip);
                }
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            View::assign('arealist', Cache::get('arealist'));
            $Find = JobFairModel::alias('job')->where(['job.id' => $id])
                ->join('job_fair_content content', 'content.jid = job.id')->field('job.*,content.content,content.about,content.job_fair_area1,content.job_fair_area2,content.job_fair_area3,content.address,content.lng,content.lat,content.transit')
                ->withAttr('sign_up_start_time', function ($v, $d) {
                    return $v ? date('Y-m-d H:m:s', $v) : '';
                })
                ->withAttr('sign_up_end_time', function ($v, $d) {
                    return $v ? date('Y-m-d H:m:s', $v) : '';
                })
                ->withAttr('start_time', function ($v, $d) {
                    return $v ? date('Y-m-d H:m:s', $v) : '';
                })
                ->withAttr('end_time', function ($v, $d) {
                    return $v ? date('Y-m-d H:m:s', $v) : '';
                })->find();
            if ($Find) {
                $Find->job_fair_area=[];
                if ($Find->job_fair_area1 && $Find->job_fair_area2 && $Find->job_fair_area3)
                    $Find->job_fair_area = [$Find->job_fair_area1, $Find->job_fair_area2, $Find->job_fair_area3];
                $Find->vip = JobFairVipModel::where(['jid' => $Find->id, 'status' => 1])->column('vid');
                $Find->contacts = JobFairContactsModel::where(['jid' => $Find->id])->select();
                $Booth = [];
                $JobFairBoothCateModel = JobFairBoothCateModel::where(['jid' => $Find->id])->select()->toArray();
                foreach ($JobFairBoothCateModel as $k => $v) {
                    $Booth[$k] = $v;
                    $Booth[$k]['show'] = 0;
                    $Booth[$k]['boothCate'] = JobFairBoothModel::where(['jid' => $Find->id, 'identifier' => $v['identifier']])->select()->toArray();
                }
                $Find->booth = $Booth;
            }
            View::assign('Find', $Find);
            View::assign('webtitle', '编辑【' . $Find->title . '】招聘会');
            return View::fetch('add');
        }
    }
    /**
     * 发布文章
     */
    public function add()
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'title'         => 'require',
                'content'         => 'require',
                'start_time'    => 'require',
                'end_time'         => 'require',
                'status'         => 'require',
                'thumb'         => 'require',
                'banner'        => 'require',
                'base_view'        => 'number|min:0',
                'base_company'        => 'number|min:0',
            ];
            $msg  =   [
                'title.require'         => '标题不能为空',
                'start_time.require'    => '请选择开始时间',
                'end_time.require'         => '请选择结束时间',
                'content.require'         => '详情不能为空',
                'status.require'         => '请选择状态',
                'thumb.require'         => '请上传封面',
                'banner.require'        => '请上传横幅',
                'base_view.number'      => '浏览数基准必须是数字',
                'base_view.min'         => '浏览数基准不能小于0',
                'base_company.number'   => '参会企业基准必须是数字',
                'base_company.min'      => '参会企业基准不能小于0'
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            if (!$D['online_registration'] && !$D['tel_registration'] && !$D['offline_registration'])
                return $this->ajaxReturn('请选择一种报名方式', -100);
            $JobFairModel = new JobFairModel;
            $JobFairModel->title                = $D['title'];
            $JobFairModel->thumb                = $D['thumb'];
            $JobFairModel->banner                = $D['banner'];
            $JobFairModel->booth_img            = $D['booth_img'];
            $JobFairModel->status                = $D['status'];
            $JobFairModel->nature                = $D['nature'];
            $JobFairModel->online_registration  = $D['online_registration'];
            $JobFairModel->tel_registration        = $D['tel_registration'];
            $JobFairModel->offline_registration = $D['offline_registration'];
            $JobFairModel->sort                    = $D['sort'];
            $JobFairModel->is_all_sign_up        = $D['is_all_sign_up'];
            $JobFairModel->booth_sum            = $D['booth_sum'];
            $JobFairModel->base_view            = $D['base_view'];
            $JobFairModel->base_people_sum         = $D['base_people_sum'];
            if (strtotime($D['sign_up_start_time']))
                $JobFairModel->sign_up_start_time = strtotime($D['sign_up_start_time']);
            if (strtotime($D['sign_up_end_time']))
                $JobFairModel->sign_up_end_time = strtotime($D['sign_up_end_time']);
            if (strtotime($D['start_time']))
                $JobFairModel->start_time = strtotime($D['start_time']);
            if (strtotime($D['end_time']))
                $JobFairModel->end_time = strtotime($D['end_time']);

            if ($D['offline_registration'] && (empty($D['job_fair_area']) || empty($D['address'])))
                return $this->ajaxReturn('当使用线下报名时必须地区和详细地址', -100);
            $JobFairContentModel = new JobFairContentModel;
            if (!empty($D['job_fair_area']) && count($D['job_fair_area']) >= 3) {
                $JobFairContentModel->job_fair_area1 = $D['job_fair_area'][0];
                $JobFairContentModel->job_fair_area2 = $D['job_fair_area'][1];
                $JobFairContentModel->job_fair_area3 = $D['job_fair_area'][2];
            }
            if (!empty($D['address']))
                $JobFairContentModel->address = $D['address'];
            $JobFairContentModel->lng = $D['lng'];
            $JobFairContentModel->lat = $D['lat'];
            $JobFairContentModel->transit = $D['transit'];
            $JobFairContentModel->content = $D['content'];
            $JobFairContentModel->about = $D['about'];
            $Contacts = [];
            if (!empty($D['contacts'])) {
                $JobFairContactsModel = new JobFairContactsModel;
                foreach ($D['contacts'] as $k => $v) {
                    $Contacts[$k] = [
                        'contacts'            =>    $v['contacts'],
                        'contacts_mobile'    =>    $v['contacts_mobile'],
                        'contacts_tel'        =>    $v['contacts_tel'],
                        'contacts_qq'        =>    $v['contacts_qq'],
                        'contacts_wechat'    =>    $v['contacts_wechat'],
                        'contacts_email'    =>    $v['contacts_email'],
                        'remarks'            =>    $v['remarks']
                    ];
                }
            }
            if ($D['tel_registration'] && empty($Contacts))
                return $this->ajaxReturn('当使用电话报名时必须设置联系人', -100);
            $BoothCate = [];
            $Booth = [];
            if (!empty($D['booth'])) {
                $booth_json = json_decode($D['booth'], true);
                if (!empty($booth_json)) {
                    $JobFairBoothModel = new JobFairBoothModel;
                    $JobFairBoothCateModel = new JobFairBoothCateModel;
                    foreach ($booth_json as $k => $v) {
                        $BoothCate[$k] = [
                            'name'                =>    empty($v['name']) ? $v['identifier'] . '区' : $v['name'],
                            'identifier'        =>    $v['identifier'],
                            'sum'                =>    $v['sum'],
                            'price'             =>  $v['price'],
                            'specifications'    =>    $v['specifications']
                        ];
                        $stock_sum = 0;
                        foreach ($v['boothCate'] as $key => $booth) {
                            $Booth[] = [
                                'identifier'        =>    $v['identifier'],
                                'index'                =>    $booth['index'],
                                'price'                =>    $booth['price'],
                                'specifications'    =>    $booth['specifications'],
                                'status'            =>    $booth['status'],
                            ];
                            if ($booth['status'])
                                $stock_sum++;
                        }
                        $BoothCate[$k]['stock_sum'] = $v['sum'] - $stock_sum;
                    }
                }
            }
            if ($D['online_registration'] && (empty($BoothCate) || empty($Booth)))
                return $this->ajaxReturn('当使用线上报名时必须设置展位', -100);
            $Vip = [];
            $VipController = VipController::getCate();
            $JobFairVipModel = new JobFairVipModel;
            $VipControllerIndex = 0;
            foreach ($VipController as $v) {
                $Vip[$VipControllerIndex] = [
                    'vid'                =>    $v->id,
                    'level'                =>    $v->level,
                    'is_company'        =>    $v->is_company
                ];
                if ($D['is_all_sign_up']) {
                    $Vip[$VipControllerIndex]['status'] = 1;
                } else {
                    $Vip[$VipControllerIndex]['status'] = in_array($D['vip'], $v->id) ? 1 : 0;
                }
                $VipControllerIndex++;
            }
            unset($D);
            unset($rule);
            unset($msg);
            unset($Validate);
            unset($result);
            unset($booth_json);
            unset($VipController);
            unset($VipControllerIndex);
            // 启动事务
            Db::startTrans();
            try {
                $JobFairModel->save();
                $JobFairContentModel->jid = $JobFairModel->id;
                $JobFairContentModel->save();
                if (!empty($Contacts)) {
                    array_walk($Contacts, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairContactsModel->saveAll($Contacts);
                }
                if (!empty($BoothCate)) {
                    array_walk($BoothCate, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothCateModel->saveAll($BoothCate);
                }
                if (!empty($Booth)) {
                    array_walk($Booth, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothModel->saveAll($Booth);
                }
                if (!empty($Vip)) {
                    array_walk($Vip, function (&$v, $k) use ($JobFairModel) {
                        $v['jid'] = $JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairVipModel->saveAll($Vip);
                }
                // 提交事务
                Db::commit();
                Baidu::post(config('web.url') . '/job-fair/detail/' . $JobFairModel->id . '.html');
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } else {
            View::assign('vip', VipController::getCate());
            View::assign('arealist', Cache::get('arealist'));
            return View::fetch();
        }
    }
    /**
     * 设置文章状态
     */
    public function setJobFairStatus($id, $status)
    {
        $JobFairModel = JobFairModel::find($id);
        $JobFairModel->status = $status;
        if ($JobFairModel->save()) {
            return $this->ajaxReturn();
        } else {
            return $this->ajaxReturn('保存失败，请重试', -100);
        }
    }
    public function setJobFailDelete($id)
    {
        $JobFairModel = JobFairModel::find($id);
        if ($JobFairModel) {
            if ($JobFairModel->delete()) {
                return $this->ajaxReturn();
            } else {
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $JobFairModel = JobFairModel::onlyTrashed()->find($id);
            if ($JobFairModel) {
                if (empty(request()->get('force'))) {
                    if ($JobFairModel->restore()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                } else {
                    if ($JobFairModel->force()->delete()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                }
            }
        }
        return $this->ajaxReturn('招聘会不存在', -100);
    }
    public function delJobFairContacts($id)
    {
        if (JobFairContactsModel::where(['id' => $id])->delete()) {
            return $this->ajaxReturn();
        } else {
            return $this->ajaxReturn('删除失败，请重试', -100);
        }
    }
    public function delJobFairBooth($id, $is_cate)
    {
        if ($is_cate) {
            $JobFairBoothCateModel = JobFairBoothCateModel::where(['id' => $id])->find();
            $JobFairBoothModel1 = JobFairBoothModel::where(['jid' => $JobFairBoothCateModel->jid, 'identifier' => $JobFairBoothCateModel->identifier])->where(['status' => 1])->count();
            $JobFairBoothModel2 = JobFairBoothModel::where(['jid' => $JobFairBoothCateModel->jid, 'identifier' => $JobFairBoothCateModel->identifier])->where(['status' => 2])->count();
            if ($JobFairBoothModel1 > 0 || $JobFairBoothModel2 > 0) {
                return $this->ajaxReturn('当前展位区域下有' . $JobFairBoothModel1 . '个锁定，' . $JobFairBoothModel2 . '个已售无法删除', -200);
            } else {
                // 启动事务
                Db::startTrans();
                try {
                    JobFairBoothCateModel::where(['id' => $id])->delete();
                    JobFairBoothModel::where(['jid' => $JobFairBoothCateModel->jid, 'identifier' => $JobFairBoothCateModel->identifier, 'status' => 0])->delete();
                    // 提交事务
                    Db::commit();
                    return $this->ajaxReturn();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->ajaxReturn('删除失败或状态不为待售', -200);
                }
            }
        } else {
            $JobFairBoothModel = JobFairBoothModel::where(['id' => $id])->find();
            // 启动事务
            Db::startTrans();
            try {
                JobFairBoothModel::where(['id' => $id, 'status' => 0])->delete();
                JobFairBoothCateModel::where(['jid' => $JobFairBoothModel->jid, 'identifier' => $JobFairBoothModel->identifier])->dec('sum')->dec('stock_sum')->update();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('删除失败或状态不为待售', -200);
            }
        }
    }
    public function boothManage()
    {
        if (request()->isAjax()) {
            if (request()->isGet()) {
                $G = request()->get();
                if (empty($G['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会', -200);
                $where = [];
                $where[] = ['job.id', '=', $G['jid']];
                $Find = JobFairController::getFind($where);
                if ($Find) {
                    return $this->ajaxReturn('', 0, $Find);
                } else {
                    return $this->ajaxReturn('招聘会不存在', -200);
                }
            }
            if (request()->isPost()) {
                $D = request()->post();
                if (empty($D['bid']))
                    return $this->ajaxReturn('未获取到展位信息', -200);
                switch ($D['status']) {
                    case 2:
                        if (empty($D['company_id']))
                            return $this->ajaxReturn('请检索要绑定的企业', -200);
                        return $this->setBoothStatusCompany($D);
                    case 1:
                        return $this->setBoothStatusLock($D);
                    default:
                        return $this->setBoothStatusUnlock($D);
                }
            }
        } else {
            $JobFair = JobFairController::getList();
            View::assign('JobFair', $JobFair->items());
            return View::fetch();
        }
    }
    public function setBoothStatusCompany($D)
    {
        $JobFairBoothModel = JobFairBoothModel::where(['id' => $D['bid']])->find();
        $JobFairBoothStatusModel = new JobFairBoothStatusModel;
        $JobFairBoothStatusModel->bid = $JobFairBoothModel->id;
        $JobFairBoothStatusModel->status = 2;
        $JobFairBoothStatusModel->company_id = $D['company_id'];
        $JobFairBoothStatusModel->old_status = $JobFairBoothModel->status;
        $JobFairBoothStatusModel->old_company_id = $JobFairBoothModel->company_id;
        $JobFairBoothModel->status = 2;
        $JobFairBoothModel->company_id = $D['company_id'];
        $JobFairBoothStatusModel->admin_uid = Session::get('AdminUser.uid');
        $JobFairCompanyModel = JobFairCompanyModel::where(['jid' => $JobFairBoothModel->jid, 'company_id' => $D['company_id']])->find();
        $JobFairModel = null;
        $JobFairCompany = null;
        if (!$JobFairCompanyModel) {
            $JobFairModel = JobFairModel::where(['id' => $JobFairBoothModel->jid])->find();
            $company_sum = JobFairCompanyModel::where(['jid' => $JobFairBoothModel->jid])->count();
            $JobFairModel->company_sum = $company_sum + 1;
            $JobFairCompany = new JobFairCompanyModel;
            $JobFairCompany->jid = $JobFairBoothModel->jid;
            $JobFairCompany->bid = $JobFairBoothModel->id;
            $JobFairCompany->company_id = $D['company_id'];
        }
        // 启动事务
        Db::startTrans();
        try {
            $JobFairBoothModel->save();
            $JobFairBoothStatusModel->save();
            if ($JobFairModel) $JobFairModel->save();
            if ($JobFairCompany) $JobFairCompany->save();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试', -200);
        }
    }
    public function setBoothStatusLock($D)
    {
        $JobFairBoothModel = JobFairBoothModel::where(['id' => $D['bid']])->find();
        if ($JobFairBoothModel->status === 0) {
            $JobFairBoothModel->status = 1;
            $JobFairBoothStatusModel = new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid = $JobFairBoothModel->id;
            $JobFairBoothStatusModel->status = 1;
            $JobFairBoothStatusModel->old_status = 0;
            $JobFairBoothStatusModel->admin_uid = Session::get('AdminUser.uid');
            // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        }
        return $this->ajaxReturn();
    }
    public function setBoothStatusUnlock($D)
    {
        $JobFairBoothModel = JobFairBoothModel::where(['id' => $D['bid']])->find();
        if ($JobFairBoothModel->status === 1) {
            $JobFairBoothModel->status = 0;
            $JobFairBoothStatusModel = new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid = $JobFairBoothModel->id;
            $JobFairBoothStatusModel->status = 0;
            $JobFairBoothStatusModel->old_status = 1;
            $JobFairBoothStatusModel->admin_uid = Session::get('AdminUser.uid');
            // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        } elseif ($JobFairBoothModel->status === 2) {
            $JobFairBoothModel->status = 0;
            $JobFairCompanyModel = JobFairCompanyModel::where(['bid' => $JobFairBoothModel->id, 'company_id' => $JobFairBoothModel->company_id])->find();
            if ($JobFairCompanyModel)
                $JobFairCompanyModel->bid = null;
            $JobFairBoothStatusModel = new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid = $JobFairBoothModel->id;
            $JobFairBoothStatusModel->status = 0;
            $JobFairBoothStatusModel->old_status = 2;
            $JobFairBoothStatusModel->old_company_id = $JobFairBoothModel->company_id;
            $JobFairBoothStatusModel->admin_uid = Session::get('AdminUser.uid');
            $JobFairModel = JobFairModel::where(['id' => $JobFairBoothModel->jid])->find();
            $is_del = false;
            if (JobFairBoothModel::where(['jid' => $JobFairBoothModel->jid, 'company_id' => $JobFairBoothModel->company_id, 'status' => 2])->count() < 2)
                $is_del = true;
            $company_sum = JobFairCompanyModel::where(['jid' => $JobFairBoothModel->jid])->count();
            $JobFairModel->company_sum = $is_del ? $company_sum - 1 : $company_sum;
            $JobFairBoothModel->company_id = null;
            // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                if ($JobFairCompanyModel) $JobFairCompanyModel->save();
                $JobFairModel->save();
                if ($is_del) JobFairCompanyModel::where(['jid' => $JobFairBoothModel->jid, 'company_id' => $JobFairBoothModel->company_id])->delete();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        }
        return $this->ajaxReturn('请刷新页面', -200);
    }
    public function getBoothStatusLog()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = ['b.bid' => $G['bid']];
            $Data = JobFairBoothStatusModel::alias('b')->where($where)
                ->join('company c', 'c.id=b.company_id', 'LEFT')
                ->join('company oldc', 'oldc.id=b.old_company_id', 'LEFT')
                ->join('admin admin', 'admin.id=b.admin_uid')
                ->field('b.*,c.logo,c.title,c.stitle,oldc.logo as old_logo,oldc.title as old_title,oldc.stitle as old_stitle,admin.nickname')
                ->order('b.id desc')->paginate(10)
                ->each(function ($v) {
                    $v['logo'] = $v['logo'] ? config('web.imgurl') . $v['logo'] : '';
                    $v['old_logo'] = $v['old_logo'] ? config('web.imgurl') . $v['old_logo'] : '';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function resumeManage()
    {
        if (request()->isAjax()) {
            if (request()->isGet()) {
                $G = request()->get();
                if (empty($G['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会', -200);
                $Field = [
                    'job.*',
                    'resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.refresh_time,resume.progress,resume.headimg_status,resume.privacy',
                    'e.salary_min,e.salary_max',
                    'nature_of_work.title as nature_of_work',
                    'job_status.title as job_status',
                    'industry.title as industry',
                    'province.title as job_province,city.title as job_city,area.title as job_area',
                    'educational_background.title as educational_background',
                    'self_description.self_description',
                    'user_info.headimg'
                ];
                $where = [];
                $where[] = ['job.jid', '=', $G['jid']];
                $Data = JobFairResumeModel::alias('job')
                    ->join('resume resume', 'resume.id=job.resume_id')
                    ->where($where)
                    ->join('user user', 'user.id=resume.uid')
                    ->join('user_info user_info', 'user_info.uid=user.id')
                    ->join('resume_self_description self_description', 'self_description.resume_id=resume.id', 'LEFT')
                    ->where(['educational_background.alias' => 'resume/educational_background'])
                    ->join('status_alias educational_background', 'educational_background.value=resume.educational_background')
                    ->where(['job_status.alias' => 'resume/job_status'])
                    ->join('status_alias job_status', 'job_status.value=resume.job_status')
                    ->join('resume_employment_intention e', 'e.resume_id=resume.id AND e.default=1', 'LEFT')
                    ->join('status_alias nature_of_work', 'nature_of_work.value=e.nature_of_work AND nature_of_work.alias=\'resume/nature_of_work\'', 'LEFT')
                    ->join('company_industry industry', 'industry.id=e.industry_id', 'LEFT')
                    ->join('area province', 'province.id = e.job_area1', 'LEFT')
                    ->join('area city', 'city.id = e.job_area2', 'LEFT')
                    ->join('area area', 'area.id = e.job_area3', 'LEFT')
                    ->field(implode(',', $Field))
                    ->order('job.id desc')->paginate($G['pageSize'])
                    ->each(function ($v) {
                        $v['age'] = getWorkExpYear($v['age']);
                        $v['work_experience_time'] = getWorkExpYear($v['work_experience_time']);
                        $v['friendly_time'] = friendly_time($v['refresh_time'], 'friendly');
                        $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                        return $v;
                    });
                if ($Data->items()) {
                    return $this->ajaxReturn('', 0, $Data);
                } else {
                    return $this->ajaxReturn('暂无数据~', -100);
                }
            }
            if (request()->post()) {
                $D = request()->post();
                if (empty($D['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会', -200);
                $JobFairModel = JobFairModel::where(['id' => $D['jid']])->find();
                if (!$JobFairModel)
                    return $this->ajaxReturn('请先选择要管理的招聘会', -200);
                $JobFairResumeModel = new JobFairResumeModel;
                $resumeList = [];
                foreach ($D['resume_id'] as $k => $v) {
                    $resumeList[] = [
                        'jid'       => $D['jid'],
                        'resume_id' => $v
                    ];
                }
                $JobFairModel->resume_sum = DB::raw('resume_sum+' . count($resumeList));
                $JobFairModel->view_people_sum = DB::raw('view_people_sum+' . count($resumeList));
                $JobFairModel->view_sum = DB::raw('view_sum+' . count($resumeList) * 2);
                // 启动事务
                Db::startTrans();
                try {
                    $JobFairResumeModel->saveAll($resumeList);
                    $JobFairModel->save();
                    // 提交事务
                    Db::commit();
                    return $this->ajaxReturn();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->ajaxReturn('添加失败', -200);
                }
            }
        } else {
            $JobFair = JobFairController::getList();
            View::assign('JobFair', $JobFair->items());
            return View::fetch();
        }
    }
    public function delResume($id)
    {
        $JobFairResumeModel = JobFairResumeModel::where(['id' => $id])->find();
        // 启动事务
        Db::startTrans();
        try {
            JobFairResumeModel::where(['id' => $id])->delete();
            JobFairModel::where(['id' => $JobFairResumeModel->jid])->dec('resume_sum')->update();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('删除失败', -200);
        }
    }
}
